package com.atguigu.gmall.realtime.dim.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.base.BaseApp;
import com.atguigu.gmall.realtime.common.bean.TableProcessDim;
import com.atguigu.gmall.realtime.common.constant.Constant;
import com.atguigu.gmall.realtime.common.util.FlinkSourceUtil;
import com.atguigu.gmall.realtime.common.util.HBaseUtil;
import com.atguigu.gmall.realtime.dim.function.DimSinkFunction;
import com.atguigu.gmall.realtime.dim.function.TableProcessFunction;
import com.ververica.cdc.connectors.mysql.source.MySqlSource;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.BroadcastConnectedStream;
import org.apache.flink.streaming.api.datastream.BroadcastStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.hadoop.hbase.client.Connection;

/**
 * @author Felix
 * @date 2024/10/29
 * Dim维度处理
 * 需要启动的进程
 *      zk、kafka、hdfs、maxwell、DimApp
 * 开发流程
 *      基本环境准备
 *      检查点相关的设置
 *      从kafka的topic_db主题中读取数据
 *      对读取的数据进行类型转换以及ETL  jsonStr->jsonObj
 *      ~~~~~~~~~~~~~~~~~~~~~~主流--业务~~~~~~~~~~~~~~~~~~~~~~~~
 *      使用FlinkCDC读取配置表配置信息
 *      对配置流进行类型转换  jsonStr->TableProcessDim实体类对象
 *      根据配置信息在HBase中建表或者删表
 *          op='c'|| op='r'  建表
 *          op='d' 删除
 *          op='u'  先删后建
 *      ~~~~~~~~~~~~~~~~~~~~~~广播流--配置~~~~~~~~~~~~~~~~~~~~~~~~
 *      广播配置流---broadcast
 *      将主流和广播流进行关联---connect
 *      对关联后的数据进行处理---process
 *          new BroadcastProcessFunction{
 *              open:预加载配置信息到configMap中-解决主流数据先到，广播流数据后到的情况
 *              processElement:处理主流数据
 *                  根据维度表表名到广播状态以及configMap中获取对应的配置信息，如果配置信息不为空，说明是维度，向下游传递 Tuple2<dataJsonObj,TableProcessDim>
 *                  在向下游传递数据前，过滤掉不需要传递的字段
 *                  在向下游传递数据前，补充type属性
 *              processBroadcastElement:处理广播流数据
 *                  op=d:从广播状态以及configMap中删除对应的配置信息
 *                  op!= d:  将配置信息放到广播状态以及configMap中
 *          }
 *      将流中的维度数据同步到HBase表中
 *          new RichSinkFunciton{
 *              invoke：
 *                  type='delete'  从hbase表中删除数据
 *                  type!='delete' 向hbase表中put数据
 *          }
 * 程序执行的流程（以对品牌维度表中的数据进行修改为例）
 *      在DimApp应用程序启动的时候，会将配置信息加载到configMap以及广播状态中
 *      当品牌维度表被修改之后，binlog会记录变化
 *      maxwell会从binlog中读取变化数据并封装为json格式字符串发送到kafka的topic_db主题
 *      DimApp会从kafka主题中读取数据进行处理
 *          判断是否是维度数据，如果说是维度数据，将维度数据发送到下游，写到HBase表中
 */
public class DimApp extends BaseApp {
    public static void main(String[] args) throws Exception {
        new DimApp().start(10002,4,"dim_app",Constant.TOPIC_DB);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> kafkaStrDS) {
        //TODO 1.对业务流中数据进行类型转换并进行简单的ETL    jsonStr->jsonObj
        SingleOutputStreamOperator<JSONObject> jsonObjDS = etl(kafkaStrDS);

        //TODO 2.使用FlinkCDC读取配置表的配置信息
        SingleOutputStreamOperator<TableProcessDim> beanDS = readTableProcess(env);

        //TODO 3.根据配置表中的配置信息在HBase中建表或者删表
        beanDS = createHBaseTable(beanDS);

        //TODO 4.广播配置流并和主流进行关联
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connect(beanDS, jsonObjDS);

        //TODO 5.将维度数据同步到HBase
        //({"tm_name":"Redmi","id":1,"type":"update"},TableProcessDim(sourceTable=base_trademark, sinkTable=dim_base_trademark, sinkColumns=id,tm_name, sinkFamily=info, sinkRowKey=id, op=r))
        write2HBase(dimDS);
    }

    private static void write2HBase(SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS) {
        dimDS.addSink(
                new DimSinkFunction()
        );
    }

    private static SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> connect(SingleOutputStreamOperator<TableProcessDim> beanDS, SingleOutputStreamOperator<JSONObject> jsonObjDS) {
        //4.1 广播配置流---broadcast
        MapStateDescriptor<String, TableProcessDim> mapStateDescriptor
                = new MapStateDescriptor<String, TableProcessDim>("mapStateDescriptor",String.class, TableProcessDim.class);
        BroadcastStream<TableProcessDim> broadcastDS = beanDS.broadcast(mapStateDescriptor);

        //4.2 将主流业务数据和广播流配置信息进行关联---connect
        BroadcastConnectedStream<JSONObject, TableProcessDim> connectDS = jsonObjDS.connect(broadcastDS);

        //4.3 对关联的数据进行处理---process
        SingleOutputStreamOperator<Tuple2<JSONObject, TableProcessDim>> dimDS = connectDS.process(
                new TableProcessFunction(mapStateDescriptor)
        );
        dimDS.print();
        return dimDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> createHBaseTable(SingleOutputStreamOperator<TableProcessDim> beanDS) {
        beanDS = beanDS.map(
                new RichMapFunction<TableProcessDim, TableProcessDim>() {
                    private Connection hBaseConn;
                    @Override
                    public void open(Configuration parameters) throws Exception {
                        hBaseConn = HBaseUtil.getHBaseConnection();
                    }

                    @Override
                    public void close() throws Exception {
                        HBaseUtil.closeHBaseConnection(hBaseConn);
                    }

                    @Override
                    public TableProcessDim map(TableProcessDim tableProcessDim) throws Exception {
                        //获取对配置表进行的操作的类型
                        String op = tableProcessDim.getOp();
                        String sinkTable = tableProcessDim.getSinkTable();

                        String[] families = tableProcessDim.getSinkFamily().split(",");

                        if("r".equals(op) || "c".equals(op)){
                            //从配置表中读取了一条配置 或者向配置表添加了一条配置   在HBase中创建对应的维度表
                            HBaseUtil.createHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable,families);
                        }else if ("d".equals(op)){
                            //从配置表中删除了一条配置 从HBase中删除对应的表
                            HBaseUtil.dropHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable);
                        }else {
                            //对配置表某条配置进行了修改   先从HBase中删除对应的表  在创建新表
                            HBaseUtil.dropHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable);
                            HBaseUtil.createHBaseTable(hBaseConn,Constant.HBASE_NAMESPACE,sinkTable,families);

                        }
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);
        return beanDS;
    }

    private static SingleOutputStreamOperator<TableProcessDim> readTableProcess(StreamExecutionEnvironment env) {
        //2.1 创建MySqlSource对象
        MySqlSource<String> mySqlSource
                = FlinkSourceUtil.getMySqlSource("gmall0522_config", "table_process_dim");

        //2.2 读取数据 封装为流
        DataStreamSource<String> mysqlStrDS
                = env.fromSource(mySqlSource, WatermarkStrategy.noWatermarks(), "mysql_source").setParallelism(1);

        //"op":"r" : {"before":null,"after":{"source_table":"spu_info","sink_table":"dim_spu_info","sink_family":"info","sink_columns":"id,spu_name,description,category3_id,tm_id","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":0,"snapshot":"false","db":"gmall0522_config","sequence":null,"table":"table_process_dim","server_id":0,"gtid":null,"file":"","pos":0,"row":0,"thread":null,"query":null},"op":"r","ts_ms":1730190858870,"transaction":null}
        //"op":"c" : {"before":null,"after":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1730190927000,"snapshot":"false","db":"gmall0522_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000002","pos":10986233,"row":0,"thread":15,"query":null},"op":"c","ts_ms":1730190927273,"transaction":null}
        //"op":"u" : {"before":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name","sink_row_key":"id"},"after":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1730190971000,"snapshot":"false","db":"gmall0522_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000002","pos":10986593,"row":0,"thread":15,"query":null},"op":"u","ts_ms":1730190971614,"transaction":null}
        //"op":"d" : {"before":{"source_table":"a","sink_table":"dim_a","sink_family":"info","sink_columns":"id,name,age","sink_row_key":"id"},"after":null,"source":{"version":"1.9.7.Final","connector":"mysql","name":"mysql_binlog_source","ts_ms":1730191008000,"snapshot":"false","db":"gmall0522_config","sequence":null,"table":"table_process_dim","server_id":1,"gtid":null,"file":"mysql-bin.000002","pos":10986979,"row":0,"thread":15,"query":null},"op":"d","ts_ms":1730191009186,"transaction":null}
        //mysqlStrDS.print();

        //2.3.对配置流中数据进行类型转换  jsonStr->实体类对象
        SingleOutputStreamOperator<TableProcessDim> beanDS = mysqlStrDS.map(
                new MapFunction<String, TableProcessDim>() {
                    @Override
                    public TableProcessDim map(String jsonStr) throws Exception {
                        //为了处理方便，先将jsonStr转换为jsonObj
                        JSONObject jsonObj = JSON.parseObject(jsonStr);
                        //获取对配置表进行的操作的类型
                        String op = jsonObj.getString("op");
                        TableProcessDim tableProcessDim = null;
                        if ("d".equals(op)) {
                            //说明从配置表中删除了一条配置信息  从before属性中获取删除前的配置
                            tableProcessDim = jsonObj.getObject("before", TableProcessDim.class);
                        } else {
                            //说明从配置表中读取了一条配置或者向配置表中添加了一条配置或者对某条配置进行了修改  从after属性中获取最新的配置
                            tableProcessDim = jsonObj.getObject("after", TableProcessDim.class);
                        }
                        tableProcessDim.setOp(op);
                        return tableProcessDim;
                    }
                }
        ).setParallelism(1);
        //beanDS.print();
        return beanDS;
    }

    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> kafkaStrDS) {
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.process(
                new ProcessFunction<String, JSONObject>() {
                    @Override
                    public void processElement(String jsonStr, ProcessFunction<String, JSONObject>.Context ctx, Collector<JSONObject> out) throws Exception {
                        try {
                            JSONObject jsonObj = JSON.parseObject(jsonStr);
                            String db = jsonObj.getString("database");
                            String type = jsonObj.getString("type");
                            String data = jsonObj.getString("data");
                            if("gmall0522".equals(db)
                                    && ("insert".equals(type)
                                    || "update".equals(type)
                                    || "delete".equals(type)
                                    || "bootstrap-insert".equals(type))
                                    && data != null
                                    && data.length() > 2
                            ){
                                out.collect(jsonObj);
                            }
                        } catch (Exception e) {
                            System.out.println("~~~属于脏数据~~~");
                        }
                    }
                }
        );
        //jsonObjDS.print();
        return jsonObjDS;
    }
}